package com.rephone.test;

import static org.junit.Assert.*;

import java.util.Optional;
import lombok.Builder;
import lombok.Data;
import org.junit.Test;

/**
 * @description:
 * @author:Ihope
 * @date: 2025-01-05 12:32
 * @version:
 */
public class OptionalTest2 {

  @Test
  public void optionalTest2() {
    Laptop laptop = new Laptop();
    Soundcard soundcard = new Soundcard();
    laptop.soundcard = Optional.ofNullable(null);
    //    soundcard.usb = Optional.ofNullable(null);

    var version =
        laptop.getSoundcard().flatMap(Soundcard::getUSB).map(USB::getVersion).orElse("UNKNOWN");

    assertEquals(version, "UNKNOWN");
  }

  @Test
  public void optionalTestIfPresent() {
    User user = User.builder().username("李四").build();
    Optional<User> optionalUser = Optional.ofNullable(user);
    optionalUser.ifPresent(System.out::println);
  }

  @Test
  public void optionalTestDefaulValue() {
    User user2 = User.builder().username("张三").build();
    Optional<User> optionalUser = Optional.ofNullable(null);
    User user = optionalUser.orElse(user2);
    assertEquals("张三", user.username);
  }

  @Test
  public void optionalTestDefaulValue2() {
    User user = User.builder().username("李四").build();
    User user2 = User.builder().username("张三").build();
    Optional<User> optionalUser = Optional.ofNullable(user);
    User user3 = optionalUser.orElse(user2);
    assertEquals("李四", user3.username);
  }

  @Test
  public void optionalTestDefaulValue3() {
    Optional<User> userOptional = Optional.of(User.builder().username("李四").build());
    String housename =
        userOptional.flatMap(User::getHouseOptional).map(House::getHousename).orElse("test");

    assertEquals("HOUSE NAME", housename);
  }

  public class Laptop {
    Optional<Soundcard> soundcard;

    public Optional<Soundcard> getSoundcard() {
      return soundcard;
    }
  }

  public class Soundcard {
    Optional<USB> usb;

    public Optional<USB> getUSB() {
      return usb;
    }
  }

  public class USB {
    public String getVersion() {
      return "version2";
    }
  }

  @Data
  @Builder
  static class User {
    String username;
    Optional<House> houseOptional;
    public Optional<House> getHouseOptional() {
      return houseOptional.of(new House("HOUSE NAME"));
    }
  }

  @Data
  @Builder
  static class House {
    String housename;
  }
}
